<?php

namespace App\Models\Member;

use App\Models\BaseModel;
use App\Models\Member\User;
use App\Models\Member\TotalBonusPool;
use Config, DB, Auth, Hash;
use App\Common\CodeHandler;

class DealRecord extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'user_id', 'amount', 'type', 'status',
        'reason', 'deal_type', 'last_balance', 'new_balance', 
        'deal_item_id', 'pay_orderid', 'order_type', 'jm_type', 'grade', 'mark',
        'channel_order_id', 'bank_order_id',
        'created_at', 'updated_at'
    ];

    // [余额]扣款
    public function deductMoney($goldRecord, $type=0){
        $goldRecord['type'] = 'out';
        $record = $this->changeInfo($goldRecord, $type=0);
        if ($record['code'] != 20000 ) {
            return $record;
        }
        
        DB::beginTransaction();
        try {
            $insert = $this->insert($record['data']);
            if ($insert && $record['data']['status'] == 1) {
                if($type == 0){
                    $keyYu = $this->getYu($record['data']['jm_type']);
                    $decrement = User::where('id', $record['data']['user_id'])->decrement($keyYu, $record['data']['amount']);//余额生效 出
                }else{
                    $key = $this->getBonusKey($type);
                    $decrement = TotalBonusPool::where('store_id',$record['data']['store_id'])->decrement($key, $record['data']['amount']);//余额生效 出
                }
                if ($decrement) {
                    DB::commit();
                    return $this->successClient($record, '[扣除]已生效交易记录生成成功!'); 
                } else {
                    return $this->errorClient($record, '[扣除]已生效交易记录生成失败!');
                }
            } else {
                DB::commit();
                return $this->successClient($record, '[扣除]未生效交易记录生成成功!'); 
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }
    // [余额]回款
    public function returnedMoney($goldRecord, $type=0){
        $goldRecord['type'] = 'in';
        $record = $this->changeInfo($goldRecord,$type);
        if ($record['code'] != 20000 ) {
            return $this->errorClient($goldRecord, '扣款数据不合法');
        }
        DB::beginTransaction();
        try {
            $insert = $this->insert($record['data']);
            if ($insert && $record['data']['status'] == 3) {
                if($type == 0){//用户表余额回款
                    $keyYu = $this->getYu($record['data']['jm_type']);
                    $increment = User::where('id',$record['data']['user_id'])->increment($keyYu, $record['data']['amount']);//余额生效 进
                }else{//总奖金池表 各项奖金池回款
                    $key = $this->getBonusKey($type);
                    $increment = TotalBonusPool::where('store_id',$record['data']['store_id'])->increment($key, $record['data']['amount']);//余额生效 进
                }
                if ($increment) {
                    DB::commit();
                    return $this->successClient($record, '[回款]已生效交易记录生成成功!'); 
                } else {
                    return $this->errorClient($record, '[回款]已生效交易记录生成失败!'.$increment);
                }
            } else {
                DB::commit();
                return $this->successClient($record, '[回款]未生效交易记录生成成功!'); 
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    // 金额 / 积分 / 军功章 统一逻辑
    private function changeInfo($goldRecord, $type=0)
    {
        $record=[];
        $record['type'] = $goldRecord['type'];
        $record['store_id'] = $goldRecord['store_id'];
        $record['user_id'] = $goldRecord['user_id'];
        $record['status'] = $goldRecord['status'];
        $record['reason'] = $goldRecord['reason'];
        $record['deal_type'] = $goldRecord['deal_type'];
        $record['deal_item_id'] = $goldRecord['deal_item_id'];
        $record['deal_user_id'] = isset($goldRecord['deal_user_id']) ? $goldRecord['deal_user_id'] : 0;
        $record['deal_get_id'] = isset($goldRecord['deal_get_id']) ? $goldRecord['deal_get_id'] : 0;
        $record['partner_time'] = isset($goldRecord['partner_time']) ? $goldRecord['partner_time'] : NULL;
        $record['order_type'] = $goldRecord['order_type'];
        $record['jm_type'] = $goldRecord['jm_type'];
        $record['grade'] = $goldRecord['grade'];
        $record['mark'] = isset($goldRecord['mark']) ? $goldRecord['mark'] : '';
        $record['amount'] = $goldRecord['amount'];
        $record['created_at'] = date('Y-m-d H:i:s');
        
        if (!isset($goldRecord['last_balance'])) {
            if($type == 0){
                $userInfo = User::where('id', $goldRecord['user_id'])->select('gold', 'jf', 'jgz')->first();
                $keyYu = $this->getYu($goldRecord['jm_type']);
                $record['last_balance'] = $userInfo[$keyYu];
            }else{
                $total = TotalBonusPool::where('store_id', $goldRecord['store_id'])->first();
                $key = $this->getBonusKey($type);
                $record['last_balance'] = $total[$key];
            }
        } else {
            $record['last_balance'] = $goldRecord['last_balance'];
        }
        $record['new_balance'] = $record['type'] == 'in' ? $record['last_balance'] + $record['amount'] : $record['last_balance'] - $record['amount'];
        if ($record['new_balance'] < 0) {
            return $this->errorClient($record, '[失败:'.$goldRecord['jm_type'].']交易后余额为负!');
        } else {
            return $this->successClient($record, '交易记录数据准备成功!'); 
        }
    }
    public function getYu($jm_type)
    {
        $str = '';
        switch ($jm_type) {
            case 1:
                $str = 'gold';
                break;
            case 2:
                $str = 'jf';
                break;
            case 3:
                $str = 'jgz';
                break;           
            default:
                # code...
                break;
        }
        return $str;
    }

    public function getList($request)
    {
        $type = $request['type'];
        $user = Auth::user()->toArray();
        $data = $this->where('user_id', $user['id'])->whereIn('status', [1, 3])->where('jm_type', $type)->orderBy('id', 'desc')->paginate(10)->toArray();

        foreach ($data['data'] as $key => $val) {
            $data['data'][$key]['amount'] = $val['type'] == 'in' ? $data['data'][$key]['amount'] : -$data['data'][$key]['amount'];
            // if ($val['jm_type'] != 2) {
                $data['data'][$key]['amount'] = $data['data'][$key]['amount'] / 100;
                $data['data'][$key]['new_balance'] = $data['data'][$key]['new_balance'] / 100;
                $data['data'][$key]['reason'] = $data['data'][$key]['deal_type'] == 3 ? $data['data'][$key]['mark'] : $data['data'][$key]['reason'];
            // }
        }

        return $this->successClient($data);
    }

    public function invest($user, $money, $reason, $pay_orderid=0, $deal_type, $deal_item_id=0)
    {
        $insertData = [];
        $insertData['store_id'] = $user['store_id'];
        $insertData['user_id'] = $user['id'];
        $insertData['amount'] = $money;
        $insertData['type'] = 'in';
        $insertData['status'] = 2;
        $insertData['reason'] = $reason;
        $insertData['deal_type'] = $deal_type;
        $insertData['last_balance'] = $user['gold'];
        $insertData['new_balance'] = $user['gold'] + $money;
        $insertData['order_type'] = 1;
        $insertData['jm_type'] = 1;
        $insertData['grade'] = $user['grade'];
        $insertData['deal_item_id'] = $deal_item_id;
        $insertData['pay_orderid'] = $pay_orderid;

        //微信直接支付订单
        if($deal_type == 41){
            $insertData['type'] = 'out';
            $insertData['status'] = 0;
            $insertData['order_type'] = 3;
            $insertData['new_balance'] = $user['gold'];//充值余额不变
        }

        return $this->create($insertData);
    }
    public function investSuccess($dealId, $openId, $money, $channelOrderId=0, $bankOrderId=0)
    {
        $data = [
            'status' => 3,
            'channel_order_id' => $channelOrderId,
            'bank_order_id' => $bankOrderId
        ];
        $deal = $this->find($dealId);
        if($deal->status == 3){
            return false;
        }
        $deal = $this->where('id', $dealId)->update($data);
        $user = User::where('open_id', $openId)->first();
        $user->gold = $user->gold + $money;
        $user->save();
    }

    public function getBonusKey($type){
        $str = '';
        switch ($type) {
            case 1:
                $str = 'bonus_pool_one_sum';
                break;
            case 2:
                $str = 'team_month_sum';
                break;
            case 3:
                $str = 'team_year_sum';
                break; 
            case 4:
                $str = 'team_recommend_sum';
                break; 
            case 5:
                $str = 'team_fund_sum';
                break;           
            default:
                # code...
                break;
        }
        return $str;
    }

    public function transfer($phone,$gold,$agentId,$payPwd,$code){
        $user = Auth::user();
        if($user->is_partner != 1) return $this->errorClient($user->id, '只有报单中心可以进行转账。');
        $agent = User::where('id',$agentId)->where('phone',$phone)->first();
        if(empty($agent)) return $this->errorClient($agentId, '收款人用户ID'.$agentId.'和收款人手机号'.$phone.'不匹配，请检查是否填写错误。');
        if($user->id == $agentId) return $this->errorClient($agentId, '收款账号与转账用户账号相同，无法转账。');
        if($agent->team_id != $user->team_id) return $this->errorClient($agent->team_id, '收款人不属于你的团队用户，无法转账。');
        if($gold < 100 || $gold > $user->gold/100) return $this->errorClient($gold,'转账金额不能少于100元，且不能超过自己的余额。'); 
        if (!Hash::check($payPwd, $user->password_pay)) return $this->errorClient('','支付密码输入错误。');
        $validateCode = CodeHandler::checkCode($user->store_id, $user->phone, $code, 'transfer');
        if (!$validateCode['res']) return $this->errorClient('','验证码无效。');
        DB::beginTransaction();
        try {
            $record = [];
            $record['store_id'] = $user->store_id;
            $record['user_id'] = $user->id;
            $record['status'] = 1;
            $record['reason'] = '转账-转给用户'.$agentId;
            $record['deal_type'] = 42;
            $record['deal_item_id'] = 0;
            $record['deal_user_id'] = $user->id;
            $record['order_type'] = 6;
            $record['jm_type'] = 1;
            $record['grade'] = $user->grade;
            $record['amount'] = $gold * 100;
            $res = $this->deductMoney($record);

            $record['user_id'] = $agentId;
            $record['status'] = 3;
            $record['reason'] = '转账-收到用户'.$user->id.'转账';
            $record['grade'] = $agent->grade;
            $result = $this->returnedMoney($record);
            if($res['code'] == $result['code'] && $res['code'] == 20000){
                DB::commit();
                return $this->successClient($record, '转账成功'); 
            }else{
                return $this->errorClient($record, '转账未生效'); 
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }
}
